<?php
declare(strict_types=1);

namespace app\api\controller\admin;

use app\common\library\Http;
use app\common\model\Area;
use app\common\model\delivery\BuyingOrder;
use app\common\model\delivery\Channel;
use app\common\model\delivery\ChannelGird;
use app\common\model\delivery\Coupon;
use app\common\model\delivery\CouponList;
use app\common\model\delivery\Customer;
use app\common\model\delivery\CustomerAddress;
use app\common\model\delivery\CustomerGoods;
use app\common\model\delivery\CustomerRegister;
use app\common\model\delivery\CustomerToker;
use app\common\model\delivery\Driver;
use app\common\model\delivery\Seller;
use app\common\model\delivery\Text;
use app\common\model\Qrcode;
use app\common\model\QrcodeScan;
use app\common\model\Third;
use app\common\model\User;
use app\common\model\UserLog;
use app\common\service\msg\WechatMsg;
use think\annotation\route\Get;
use think\annotation\route\Group;
use think\annotation\route\Post;
use think\facade\Db;

#[Group("admin/admin")]
class Admin extends Base {
    #[Get('getregister')]
    public function getregister($id)
    {
        $customer=CustomerRegister::find($id);
        if($customer->channel_id!=$this->channel->id){
            $this->error('非法操作');
        }
        if($this->seller && $customer->seller_id!=$this->seller->id){
            $this->error('非法操作');
        }
        if($customer->status){
            $this->error('该申请已经审核通过了！');
        }
        $customer->info=json_decode($customer['info'],true);
        $customer->channel=Channel::find($customer->channel_id);
        if($customer->seller_id){
            $customer->seller=Seller::find($customer->seller_id);
        }
        $customer->settle_type=Channel::SETTLE_TYPE;
        $customer->gird=ChannelGird::where(['channel_id'=>$customer->channel_id])->select();
        $customer->user=User::find($customer->user_id);
        $this->success('',$customer);
    }

    #[Post('shenhe')]
    public function shenhe()
    {
        $register_id=$this->request->post('register_id');
        $register=CustomerRegister::find($register_id);
        if($register->channel_id!=$this->channel->id){
            $this->error('非法操作');
        }
        if($this->seller && $register->seller_id!=$this->seller->id){
            $this->error('非法操作');
        }
        if($register->status){
            $this->error('该申请已经审核通过了！');
        }
        $info=$this->request->post('info');
        $cover_url=null;
        $license_photo=null;
        if($info['customer_type']=='company'){
            if(empty($info['cover_url'])){
                $this->error('请上传客户门头');
            }
            if(empty($info['license_photo'])){
                $this->error('请上传营业执照');
            }
            $cover_url=$info['cover_url'][0]['url'];
            $license_photo=$info['license_photo'][0]['url'];
        }
        $customerGoods=[];
        foreach ($info['goods'] as $goods){
            foreach ($goods['spec'] as $spec){
                $customerGoods[]=[
                    'goods_id'=>$goods['id'],
                    'spec_id'=>$spec['id'],
                    'price'=>$spec['price'],
                ];
            }
        }
        $customer=new Customer();
        $customerinfo=[
            'channel_id'=>$register->channel_id,
            'seller_id'=>$register->seller_id??null,
            'customer_type'=>$info['customer_type'],
            'user_id'=>$info['user_id'],
            'name'=>$info['name'],
            'cover_url'=>$cover_url,
            'license'=>$info['license'],
            'license_photo'=>$license_photo,
            'province_id'=>$info['region'][0],
            'city_id'=>$info['region'][1],
            'area_id'=>$info['region'][2],
            'gird_id'=>$info['gird_id'],
            'address'=>$info['address'],
            'latitude'=>$info['latitude'],
            'longitude'=>$info['longitude'],
            'contact'=>$info['contact'],
            'mobile'=>$info['mobile'],
            'settle_type'=>$info['settle_type'],
            'bill_date'=>$info['bill_date'],
            'status'=>'normal',
        ];
        $err='';
        Db::startTrans();
        try {
            $register->status=1;
            $register->save();
            $customer->save($customerinfo);
            foreach ($customerGoods as $k=>$v){
                $customerGoods[$k]['customer_id']=$customer->id;
            }
            (new CustomerGoods())->saveAll($customerGoods);
            $mergename=Area::find($info['region'][2])->mergename;
            $addressinfo=[
                'customer_id'=>$customer->id,
                'province_id'=>$info['region'][0],
                'city_id'=>$info['region'][1],
                'area_id'=>$info['region'][2],
                'mergename'=>$mergename,
                'detail'=>$info['address'],
                'longitude'=>$info['longitude'],
                'latitude'=>$info['latitude'],
                'info'=>json_encode([
                    'title'=>$mergename,
                    'address'=>$info['address']
                ],JSON_UNESCAPED_UNICODE),
                'contact'=>$info['contact'],
                'mobile'=>$info['mobile'],
                'sex'=>1,
                'is_default'=>1
            ];
            (new CustomerAddress())->save($addressinfo);
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            $err=$e->getMessage();
        }
        if($err){
            $this->error('审核失败：'.$err);
        }
        WechatMsg::customerApplySuccess($customer);
        $this->success('审核成功');
    }


    #[Get('driver')]
    public function driver($id,$page)
    {
        $gird=ChannelGird::find($id);
        $did=$gird->drivers?explode(',',$gird->drivers):[];
        $driver=[];
        if($page==1){
            $driver=Driver::where('channel_id',$this->channel->id)
            ->whereIn('id',$did)
            ->select()
            ->toArray();
            foreach ($driver as &$value){
                $value['is_check']=1;
            }
        }
        $offset=($page-1)*10;
        $driver=array_merge($driver,Driver::limit($offset,10)
            ->order('id desc')
            ->where(['channel_id'=>$this->channel->id,'status'=>'normal'])
            ->whereNotIn('id',$did)
            ->select()
            ->toArray()
        );
        $this->success('',$driver);
    }

    #[Post('setdriver')]
    public function setdriver()
    {
        $postdata=$this->request->post();
        $gird=ChannelGird::find($postdata['id']);
        if(count($postdata['driver'])==0){
            $this->error('至少选择一名司机');
        }
        $gird->drivers=implode(',',$postdata['driver']);
        $gird->save();
        $this->success('操作成功');
    }

    #[Get('gird')]
    public function gird()
    {
        $gird=ChannelGird::where('channel_id',$this->channel->id)->select();
        $driver=Driver::where('channel_id',$this->channel->id)->select();
        foreach ($gird as &$value){
            if(!$value->drivers){
                $value->drivers=[];
                continue;
            }
            $driverids=explode(',',$value->drivers);
            $drivers=[];
            foreach ($driver as $dr){
                if(in_array((string)$dr->id,$driverids)){
                    $drivers[]=$dr;
                }
            }
            $value->drivers=$drivers;
        }
        $this->success('',$gird);
    }

    #[Get('mystore')]
    public function mystore()
    {
        $list=Db::name('customer')->where(function ($query){
            $query->where('channel_id',$this->channel->id);
            if($this->seller){
                $query->where('seller_id',$this->seller->id);
            }
        })->select()->toArray();
        $time=time();
        foreach ($list as $key=>$value){
            //30天内新注册的为新用户
            if(($time-$value['createtime'])<30*24*3600) {
                $list[$key]['isnew'] = 1;
            }else{
                $list[$key]['isnew'] = 0;
            }
        }
        $this->success('',$list);
    }

    #[Post('adddriver')]
    public function adddriver()
    {
        $postdata=$this->request->post();
        if(!$postdata['user_id']){
            $this->error('绑定微信为必填项目');
        }
        $driver=Driver::where(['channel_id'=>$this->channel->id,'user_id'=>$postdata['user_id']])->find();
        if($driver){
            $this->error('该微信已经绑定了别的司机');
        }
        $postdata['channel_id']=$this->channel->id;
        $postdata['status']='normal';
        (new Driver())->save($postdata);
        $this->success('添加成功');
    }


    #[Get('tokerlist')]
    public function tokerlist()
    {
        $list=CustomerToker::with(['history'])->whereIn('status',[1,2,3])->where(['channel_id'=>$this->channel->id])->select();
        $this->success('',$list);
    }

    #[Post('toker')]
    public function toker()
    {
        $postdata=$this->request->post();
        if($postdata['id']){
            unset($postdata['createtime']);
            unset($postdata['updatetime']);
            unset($postdata['deletetime']);
            $toker=CustomerToker::find($postdata['id']);
            if(count($postdata['img'])>0){
                $postdata['img']=$postdata['img'][0]['url'];
            }else{
                $this->error('请上传门店门头照片');
            }
            $user=$this->auth->nickname;
            if($this->seller){
                $user=$this->seller->realname;
            }
            $remark=Text::get($toker['remark']);
            Text::where(['id'=>$toker['remark']])->delete();
            array_push($remark,[
                'time'=>date('Y-m-d H:i',time()),
                'user'=>$user,
                'yiyuan'=>$postdata['yiyuan'],
                'status'=>$postdata['status'],
                'remark'=>$postdata['remark']
            ]);
            $postdata['remark']=Text::add($remark,'customer_toker');
            $toker->save($postdata);
            $this->success('修改成功');
        }else{
            unset($postdata['id']);
            $postdata['channel_id']=$this->channel->id;
            $user=$this->auth->nickname;
            if($this->seller){
                $postdata['seller_id']=$this->seller->id;
                $user=$this->seller->realname;
            }
            $remark=Text::add(array([
                'time'=>date('Y-m-d H:i',time()),
                'user'=>$user,
                'yiyuan'=>$postdata['yiyuan'],
                'status'=>$postdata['status'],
                'remark'=>$postdata['remark']
            ]),'customer_toker');
            $postdata['remark']=$remark;
            if(count($postdata['img'])>0){
                $postdata['img']=$postdata['img'][0]['url'];
            }else{
                $this->error('请上传门店门头照片');
            }
            $appkey=site_config("addons.qqmap_key");
            $url="https://apis.map.qq.com/ws/geocoder/v1/?location={$postdata['latitude']},{$postdata['longitude']}&key={$appkey}";
            $result=Http::get($url);
            $locat=$result->content;
            if($locat['status']==0){
                $area=$locat['result']['address_component'];
                $postdata['province']=$area['province'];
                $postdata['city']=$area['city'];
                $postdata['district']=$area['district'];
            }
            (new CustomerToker())->save($postdata);
            $this->success('标注成功');
        }
    }

    #[Get('deltoker')]
    public function deltoker($id)
    {
        $toker=CustomerToker::find($id);
        if($this->seller && $toker->seller_id!=$this->seller->id){
            $this->error('不是你的标注，禁止删除');
        }
        $toker->delete();
        $this->success('删除成功');
    }

    #[Get('qrcode')]
    public function qrcode()
    {
        $foreign_key=json_encode([
            'user_id'=>$this->auth->id,
            'channel_id'=>$this->channel->id,
            'seller_id'=>$this->seller?$this->seller->id:''
        ],JSON_UNESCAPED_UNICODE);
        $qrcode=Qrcode::createQrcode(Qrcode::TYPE('推荐用户'),$foreign_key,24*3600*365);
        $config=[
            'appid'=>site_config("delivery.miniapp_id"),
            'appsecret'=>site_config("delivery.miniapp_secret"),
        ];
        $mini=new \WeMini\Qrcode($config);
        $path='pages/index/register?qrcode='.$qrcode->id;
        $content=$mini->createMiniPath($path,600);
        header('Content-Type:image/jpg');
        echo $content;
        exit;
    }

    #[Get('addWxuser')]
    public function addWxuser()
    {
        $foreign_key=$this->request->get('foreign_key');
        $json=[
            'key'=>$foreign_key,
            'channel'=>$this->channel->title
        ];
        $qrcode=Qrcode::createQrcode(Qrcode::TYPE('绑定第三方账号'),$json,5*60);
        $config=[
            'appid'=>site_config("delivery.miniapp_id"),
            'appsecret'=>site_config("delivery.miniapp_secret"),
        ];
        $mini=new \WeMini\Qrcode($config);
        $path='pages/index/binduser?qrcode='.$qrcode->id;
        $content=$mini->createMiniPath($path,600);
        header('Content-Type:image/jpg');
        echo $content;
        exit;
    }

    #[Get('getScanUser')]
    public function getScanUser()
    {
        $foreign_key=$this->request->get('foreign_key');
        $scan=QrcodeScan::where(['type'=>Qrcode::TYPE('绑定第三方账号'),'foreign_key'=>$foreign_key])->find();
        if($scan){
            $third=Third::withJoin(['user'],'inner')->where(['platform'=>Third::PLATFORM('微信小程序'),'openid'=>$scan->openid])->find();
            if($third){
                $this->success('',$third->user);
            }else{
                $this->error();
            }
        }
        $this->error();
    }

    #[Get('coupon')]
    public function coupon()
    {
        $list=Coupon::where(['channel_id'=>$this->channel->id,'status'=>'normal'])->select();
        $this->success('',$list);
    }

    #[Post('sendCoupon')]
    public function sendCoupon()
    {
        $customer_id=$this->request->post('customer_id');
        $coupon_id=$this->request->post('coupon_id');
        $number=$this->request->post('number');
        $coupon=Coupon::find($coupon_id);
        $customer=Customer::find($customer_id);
        $user_id=explode(',',$customer->user_id);
        Db::startTrans();
        try{
            CouponList::send($customer_id,$coupon,$number,'服务商管理后台发放');
            foreach ($user_id as $uid){
                if($coupon->balance){
                    UserLog::addScoreLog($uid,'add',$coupon->balance,'','服务商发放会员卡赠送积分');
                }
                break;
            }
            Db::commit();
        }catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('发券成功');
    }
}